package service

import (
	"errors"
	"fmt"
	"gitee.com/CrazyMage/blog-service/global"
	"gitee.com/CrazyMage/blog-service/internal/model"
	"gitee.com/CrazyMage/blog-service/pkg/app"
	"github.com/jinzhu/gorm"
	"log"
)

type LoginReq struct {
	Account  string `form:"account" json:"account"`
	Email    string `form:"email" json:"email"`
	Password string `form:"password" json:"password"`
}

type LoginResp struct {
	Token string `json:"token"`
}

type RegisterReq struct {
	NikeName string `json:"nike_name" form:"nike_name" binding:"required"`
	Account  string `json:"account" form:"account" binding:"required"`
	Email    string `json:"email" form:"email" binding:"required,email"`
	Password string `json:"password" form:"password" binding:"min=6"`
}
type RegisterResp struct {
	ID uint `json:"id"`
}

type CloseAccountReq struct {
	ID uint `uri:"id" binding:"required"` // 关键：uri 标签
}

type CloseAccountResp struct {
	ID uint `json:"id"`
}

const (
	// StatusClose 为用户状态注销
	StatusClose = 3
)

func (svc *Service) Login(req *LoginReq) (LoginResp, error) {
	if req.Email == "" && req.Password == "" {
		log.Println("email or password is required")
		return LoginResp{}, errors.New("email or password is required")
	}

	var user *model.User
	var err error

	//邮箱登陆
	if req.Email != "" {
		user, err = svc.dao.GetUserByEmail(req.Email)
		if err != nil {
			return LoginResp{Token: ""}, err
		}

		if user.Password != req.Password {
			return LoginResp{Token: ""}, errors.New("password error")
		}

	}

	//账户登陆
	if req.Account != "" {
		user, err = svc.dao.GetUserByAccount(req.Account)
		if err != nil {
			return LoginResp{Token: ""}, err
		}

		if user.Password != req.Password {
			return LoginResp{Token: ""}, errors.New("password error")
		}

	}

	//登陆成功
	token, err := app.GenerateToken("eddycjy", global.JWTSetting.Secret, user.ID)
	if err != nil {
		return LoginResp{Token: ""}, err
	}
	return LoginResp{Token: token}, err

}

func (svc *Service) Register(req *RegisterReq) (*RegisterResp, error) {

	// 1. 检查邮箱是否已注册
	existingUser, err := svc.dao.GetUserByEmail(req.Email)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("failed to check email in: %w", err)
	}
	if existingUser != nil {
		return nil, errors.New("the email is already in use")
	}

	// 2. 检查账号是否已存在
	existingUser, err = svc.dao.GetUserByAccount(req.Account)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("failed to check account: %w", err)
	}
	if existingUser != nil {
		return nil, errors.New("the account is already in use")
	}

	// 3. 创建用户
	newUser := model.User{
		NickName: req.NikeName,
		Account:  req.Account,
		Email:    req.Email,
		Password: req.Password, // todo  密码应该先加密
	}

	if err = svc.dao.CreateUser(&newUser); err != nil {
		return nil, fmt.Errorf("failed to create user: %w", err)
	}

	return &RegisterResp{
		ID: newUser.ID, // 建议返回用户ID
	}, nil
}

func (svc *Service) CloseAccount(req *CloseAccountReq) (*CloseAccountResp, error) {
	values := map[string]interface{}{
		"status": StatusClose,
	}

	var rowsAffected int64
	var err error

	if rowsAffected, err = svc.dao.UpdateUserByFields(req.ID, values); err != nil {
		return nil, fmt.Errorf("failed to update user: %w", err)
	}

	if rowsAffected == 0 {
		return nil, errors.New("user not found or already closed")
	}

	if rowsAffected, err = svc.dao.DeleteUserById(req.ID); err != nil {
		return nil, fmt.Errorf("failed to delete user: %w", err)
	}

	if rowsAffected == 0 {
		return nil, errors.New("user not found or already closed")
	}

	return &CloseAccountResp{req.ID}, nil

}
